<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 管理员控制器
 * 
 * 包含管理员的列表信息显示，信息修改，和添加新管理员
 * 
 * @author wwj
 * @version 1.0.1 2012-11-8
 *
 */
class Manager extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		
		$this->check_login();
		
		// 验证权限
		$this->verify_purview(PURVIEW_MANAGER);
		
		$this->load->model('manager_m');
		
		// 加载管理员的语言包
		$this->load->language('manager');
		
	}
	
	function index($page = '')
	{
		$this->manage($page);
	}
	
	/**
	 * 显示管理员列表
	 * @param int $page 要显示的页码
	 */
	function manage($page = '')
	{
		// 获取要显示的页数
		$page           = empty($page) ? 1 : abs(intval($page));
		
		// 组织分页信息
		$config['base_url']		= base_url('manager/');
		$config['total_rows']	= $this->manager_m->get_manager_count();
		
		$page_data = $this->get_page($config);
		$data['page'] 	= $page_data['page'];

		// 查询管理员
		$managers      = $this->manager_m->show_manager($page_data['limit']);
		
		// 管理员信息列表数组
		$i = 1;
		foreach ($managers as $key => $row)
		{
			$managers[$key]['ordernum'] = ($page - 1) * $page_data['per_page'] + $i;
			$managers[$key]['lastlogintime'] = date(DATE_FORMAT, $row['lastlogintime']);
			$managers[$key]['logintime'] = date(DATE_FORMAT, $row['logintime']);
			//$managers[$key]['islocked'] = $row['islocked'] == 0 ? $this->lang->line('manager_lock_no') : $this->lang->line('manager_lock_yes');
			$i++;
		}
		
		$data['manager_list']	= $managers;
		$data['header'] 		= $this->header;
		$data['title']			= $this->lang->line('manager_title_list');
		$data['page_label']		= $this->lang->line('manager_page_label');
		$data['nav_label'] 		= $this->lang->line('com_navigate_label');
		$this->load->view('manager_list',$data);
	}
	
	/**
	 * AJAX删除管理员
	 */
	function delete_action()
	{
		// 对表单数据做判断
		$validate = $this->validation(array(array('field' => 'id[]', 'label' => 'lang:manager_id', 'rules' => 'trim|required|is_natural|xss_clean')));
		if (TRUE !== $validate)
		{
			echo $this->array2json(TRUE, $validate);
			return ;
		}
		
		// 获取管理员ID值，并放入数组
		$manager['id'] = $this->input->post('id');
		
		foreach($manager['id'] as $id)
		{
			if($this->is_current_manager($id))
			{
				echo $this->array2json(TRUE, $this->lang->line('manager_unable_delete_youself'));
				return ;
			}
			
			if(self::ADMIN_ID === (int)$id)
			{
				echo $this->array2json(TRUE, $this->lang->line('manager_unable_delete_admin'));
				return ;
			}
		}
		
		if ($this->manager_m->delete_manager($manager))
		{
			echo $this->array2json(FALSE, $this->lang->line('msg_operation_success'));
			return ;
		}
		else
		{
			echo $this->array2json(TRUE, $this->lang->line('msg_operation_failed'));
			return ;
		}
	}
	
	/**
	 * 管理员编辑显示页面
	 * @param int $manager_id 管理员ID
	 */
	function edit($id)
	{
		$manager_id['id'] = intval($id);
		if (empty($manager_id))
		{
			$this->_show_message('', $this->lang->line('manager_id_unable_empty'), 'goback');
		}
		
		// 查询管理员信息
		$manager = $this->manager_m->get_manager($manager_id);
		if (empty($manager))
		{
			$this->_show_message('', $this->lang->line('manager_does_not_exist'), 'goback');
		}
		$data = array (
					
				'header' => $this->header,
				'title' => $this->lang->line('manager_title_edit'),
				'page_label' => $this->lang->line('manager_page_label'),
				'nav_label' => $this->lang->line('com_navigate_label'),
				'redirect' => $this->get_referer_url(),
				'manager' => $manager
		);
		$this->load->view('manager_edit', $data);
	}
	
	/**
	 * 编辑管理员信息
	 */
	function edit_action()
	{
		$redirect = empty($_GET['redirect']) ? base_url('manager') : $_GET['redirect'];
		
		$verify = array(
				array('field' => 'password_old', 'label' => 'manager_origin_password', 'rules' => 'trim|min_length[6]|max_length[20]'),
				array('field' => 'password', 'label' => 'lang:manager_password', 'rules' => 'trim|min_length[6]|max_length[20]|matches[password_confirm]'),
				array('field' => 'purview[]', 'label' => 'lang:manager_purview', 'rules' => 'trim|is_natural_no_zero'),
				array('field' => 'remark', 'label' => 'lang:com_remark', 'rules' => 'trim|max_length[30]')
		);
		
		$validate = $this->validation($verify);
		if (TRUE !== $validate)
		{
			$this->_show_message(base_url('manager/manage'), $validate, 'goback');
		}
		
		$manager = $this->input->post();
		if ($manager && isset($manager['s_edit_action']))
		{
			$manager_id = (int)$manager['id'];
			
			// 限制对admin管理员的操作，admin自己不限制
			if(self::ADMIN_ID === $manager_id && $this->session->userdata('uid') > self::ADMIN_ID)
			{
				echo $this->_show_message(base_url('manager/manage'), $this->lang->line('manager_operation_deny'), 'goback');
				return ;
			}
			
			// 判断原密码是否为空，为空不更新密码
			if (!empty($manager['password_old']))
			{
				// 判断两次输入密码是否相同
				if ((strlen($manager['password']) < 6) || (strcmp($manager['password'], $manager['password_confirm']) != 0))
				{
					$this->_show_message(base_url('manager'), $this->lang->line('manager_password_different'), 'goback');
				}
				
				// 查询出此管理员的原密码，判断原密码是否正确
				$manager['password_old'] = strtolower(md5($manager['password_old'] . SECRET_KEY));
				$m = $this->manager_m->get_manager(array('id' => $manager_id, 'password' => $manager['password_old']));
				if (empty($m))
				{
					$this->_show_message(base_url('manager'), $this->lang->line('manager_password_wrong'), 'goback');
				}
				
				// 创建新密，清除数组中无用的数据
				$manager['password'] = strtolower(md5($manager['password'] . SECRET_KEY));
			}
			else
			{
				unset($manager['password']);
			}
			
			// 处理管理员权限，合并管理权限，各个权限相加，相当于对所有权限进行按位或运算
			if (isset($manager['purview']) && !empty($manager['purview']))
			{
				$manager['purview'] = (int)array_sum($manager['purview']);
			}
			else 
			{
				$manager['purview'] = 0;
			}
			
			unset($manager['s_edit_action']);
			unset($manager['password_old']);
			unset($manager['password_confirm']);
			unset($manager['id']);
			
			//var_dump($manager);exit;
			// 更新管理员信息
			$result = $this->manager_m->update_manager(array('id' => $manager_id), $manager);
			$this->_show_message($redirect, $this->lang->line('msg_operation_success'));
		}
		else
		{
			$this->_show_message(base_url('manager'), $this->lang->line('error_invalid_post'));
		}
		
	}
	
	/**
	 * 显示添加管理员页面
	 * 
	 */
	function add()
	{
		$data = array (
			
				'header' => $this->header,
				'title' => $this->lang->line('manager_title_add'),
				'page_label' => $this->lang->line('manager_page_label'),
				'nav_label' => $this->lang->line('com_navigate_label')
		);
		$this->load->view('manager_add', $data);
	}

	/**
	 * 添加管理员业务处理
	 */
	function add_action()
	{
		$verify = array(
				array('field' => 'loginname', 'label' => 'lang:manager_login_name', 'rules' => 'trim|required|min_length[5]|max_length[20]|alpha_dash'),
				array('field' => 'password', 'label' => 'lang:manager_password', 'rules' => 'trim|required|min_length[6]|max_length[20]|matches[password_confirm]'),
				array('field' => 'purview[]', 'label' => 'lang:manager_purview', 'rules' => 'trim|is_natural_no_zero'),
				array('field' => 'remark', 'label' => 'lang:com_remark', 'rules' => 'trim|max_length[30]')
		);
		
		$validate = $this->validation($verify);
		if (TRUE !== $validate)
		{
			$this->_show_message(base_url('manager/add'), $validate, 'goback');
		}
		
		$manager = $this->input->post();
		if ($manager && isset($manager['s_add_action']))
		{
			// 判断两次输入密码是否相同
			if (strcmp($manager['password'], $manager['password_confirm']) != 0)
			{
				$this->_show_message(base_url('manager'), $this->lang->line('manager_password_different'), 'goback');
			}
			
			// 查询要管理员的名称是否存在
			$m = $this->manager_m->get_manager(array('loginname' => $manager['loginname']));
			if (!empty($m))
			{
				$this->_show_message(base_url('manager'), $this->lang->line('manager_loginname_exist'), 'goback');
			}
			
			// 对管理员的密码做加密处理
			$manager['password'] = strtolower(md5($manager['password'] . SECRET_KEY));
			
			// 处理管理员权限，合并管理权限，各个权限相加，相当于对所有权限进行按位或运算
			if (isset($manager['purview']) && !empty($manager['purview']))
			{
				$manager['purview'] = (int)array_sum($manager['purview']);
			}
			
			// 清除数组中无用的数据，添加相关信息
			unset($manager['s_add_action']);
			unset($manager['password_confirm']);
			
			// 添加管理员信息
			$result = $this->manager_m->insert_manager($manager);
			if ($result != FALSE)
			{
				$this->_show_message(base_url('manager'), $this->lang->line('msg_operation_success'));
			}
		}
		else
		{
			$this->_show_message(base_url('manager'), $this->lang->line('error_invalid_post'));
		}
	}
	
	/**
	 * ajax锁定或解锁管理员
	 */
	function lock_action()
	{
		// 对提交数据做判断
		$verify = array(
					array('field' => 'id', 'label' => 'lang:manager_id', 'rules' => 'trim|required|is_natural|xss_clean'),
					array('field' => 'islocked', 'label' => 'lang:manager_islocked_empty', 'rules' => 'trim|required|is_natural')
				);
		$validate = $this->validation($verify);
		if (TRUE !== $validate)
		{
			echo $this->array2json(TRUE, $validate);
			return ;
		}
		
		$manager 	= $this->input->post();
		$id['id'] = (int)$manager['id'];
		
		// 限制对admin管理员的操作
		if(self::ADMIN_ID === $id['id'])
		{
			echo $this->array2json(TRUE, $this->lang->line('manager_operation_deny'));
			return ;
		}
		unset($manager['id']);
		$manager['islocked'] = (int)$manager['islocked'];
		if ($this->manager_m->update_manager($id, $manager))
		{
			echo $this->array2json(FALSE, $this->lang->line('msg_operation_success'));
			return ;
		}
		else
		{
			echo $this->array2json(TRUE, $this->lang->line('msg_operation_failed'));
			return ;
		}
	}
	
	/**
	 * 判断所给的id是否是当前管理员的id
	 * @param int $id
	 * @return boolean
	 */
	function is_current_manager($id)
	{
		return $this->session->userdata('uid') == (int)$id;
	}
	
}

/* End of file manager.php */
/* Location: ./application/admin/controllers/manager.php */
